package com.atguigu.stack;

/**
 * 使用栈模拟计算器一位数、多位数的计算流程
 *
 * @author WangJX
 * @version 1.0
 * @date 2019/9/29 22:46
 */
public class Calculator {

    /**
     * 判断运算符的优先级
     *
     * @return
     */
    public static int priority(int oper) {
        if (oper == '*' || oper == '/') {
            return 1;
        } else if (oper == '+' || oper == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    /**
     * 判断是运算符还是数字
     *
     * @param val 插入一个数字或者运算符
     * @return true：运算符 false：数字
     */
    public static boolean isoper(char val) {
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    /**
     * 根据运算符号计算2数结果
     *
     * @param num1 第一个数
     * @param num2 第二个数
     * @param oper 运算符
     * @return 运算结果
     */
    public static int cal(int num1, int num2, int oper) {
        int res = 0;
        switch (oper) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
            default:
                break;
        }
        return res;
    }

    public static int count(String word) {
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);

        String expression = word;
        int index = 0;
        int num1 = 0;   //存放第一个数
        int num2 = 0;   //存放第二个数
        int oper = 0; //存放运算符
        char ch = ' ';
        String keepNumber = "";
        while (true) {
            //获得运算式中的一个个字符
            ch = expression.substring(index, index + 1).charAt(0);

            //判断截取到的是不是()
            if (ch == '(') {
                //进行括号运算
                //如果截取到括号，从左括号“（”开始截取到右括号“）”字符先进行运算
                String substring = expression.substring(index + 1, expression.indexOf(")"));
                //把计算的结果的值返回出来
                int count = count(substring);
                //把括号中计算出的结果的值放入栈中
                numStack.push(count);
                //重新跟新下index值，从右括号“）”右边进行运算
                index = expression.indexOf(")");

            }else {
                //判断截取到的是运算符
                if (isoper(ch)) {
                    //判断运算符栈是否为空
                    if (operStack.isEmpty()) {
                        //为空的话直接放入运算符栈
                        operStack.push(ch);
                    } else {    //如果不为空则比较top位和要加入位的运算优先级
                        //如果刚获得的运算符小于等于top的运算符
                        //后位的优先级比前位的小，就需要先把前位的值算出来 6*2-1
                        if (priority(ch) <= priority(operStack.peek())) {
                            //pop出numstack中的两个值进行计算
                            num1 = numStack.pop();
                            num2 = numStack.pop();
                            oper = operStack.pop();
                            int val = cal(num1, num2, oper);
                            numStack.push(val);
                            operStack.push(ch);
                        } else {    //如果刚获得的运算符大于top指向的运算符
                            //放入运算符栈
                            operStack.push(ch);
                        }
                    }
                } else {    //如果是数字直接放入数字栈
                    //TODO 第一种方法     一位数运算
                    //因为读取到的是字符，字符到数字差为48，查看ASCII表
                    //numStack.push(ch - 48);  //用这种方法入栈会出现多位数计算错误

                    keepNumber += ch;
                    //TODO 第二种方法     多位数运算
                    //判断所在的数字是否在最后位，在最后直接入栈
                    if (index == expression.length() - 1) {
                        numStack.push(Integer.parseInt(keepNumber));
                    } else {
                        //判断下一位是否是字符
                        if (isoper(expression.substring(index + 1, index + 2).charAt(0))) {
                            //如果后一位是运算符则入栈
                            numStack.push(Integer.parseInt(keepNumber));
                            //清空
                            keepNumber = "";
                        }
                    }
                }
            }
            index++;
            if (index >= expression.length()) {
                break;
            }
        }

        //把数字和运算符逐个取出并计算
        while (true) {
            if (operStack.isEmpty()) {
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            int val = cal(num1, num2, oper);
            numStack.push(val);
        }

//        System.out.printf("计算：%s = %d", expression, numStack.pop());

        return numStack.pop();
    }

    public static void main(String[] args) {
        String s = "(70+2)*6-2";
        int count = count(s);
        System.out.printf("计算：%s = %d", s, count);
    }
}


class ArrayStack2 {
    int top = -1;   //指向栈的最顶端
    int[] stack;    //存储数据
    int maxSize;

    public ArrayStack2(int size) {
        this.maxSize = size;
        this.stack = new int[maxSize];
    }

    /**
     * 判断栈是否满
     *
     * @return
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 判断栈是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 添加数据
     *
     * @param value
     */
    public void push(int value) {
        if (isFull()) {
            throw new RuntimeException("栈已满");
        }
        top++;
        stack[top] = value;
    }

    /**
     * 取数据
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 显示栈数据
     */
    public void show() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d] = %d\n", i, stack[i]);
        }
    }

    /**
     * 偷看top指向的数据
     *
     * @return
     */
    public int peek() {
        return stack[top];
    }
}